package com.lzw.bluetoothpractice.Fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lzw.bluetoothpractice.AAChartCoreLib.AAChartCreator.AAChartModel;
import com.lzw.bluetoothpractice.AAChartCoreLib.AAChartCreator.AAChartView;
import com.lzw.bluetoothpractice.AAChartCoreLib.AAChartCreator.AASeriesElement;
import com.lzw.bluetoothpractice.AAChartCoreLib.AAChartEnum.AAChartSymbolType;
import com.lzw.bluetoothpractice.AAChartCoreLib.AAChartEnum.AAChartType;
import com.lzw.bluetoothpractice.AAChartCoreLib.AAChartEnum.AAChartZoomType;
import com.lzw.bluetoothpractice.AAChartCoreLib.AAOptionsModel.AADataElement;
import com.lzw.bluetoothpractice.AAChartCoreLib.AAOptionsModel.AAMarker;
import com.lzw.bluetoothpractice.AAChartCoreLib.AAOptionsModel.AAScrollablePlotArea;
import com.lzw.bluetoothpractice.AAChartCoreLib.AATools.AAGradientColor;
import com.lzw.bluetoothpractice.AAChartCoreLib.AATools.AALinearGradientDirection;
import com.lzw.bluetoothpractice.Activitys.AngleActivity;
import com.lzw.bluetoothpractice.Activitys.DoctorsOnlineActivity;
import com.lzw.bluetoothpractice.Activitys.HealthyMessagesActivity;
import com.lzw.bluetoothpractice.Activitys.MyDoctorsActivity;
import com.lzw.bluetoothpractice.Activitys.RecoveryForumActivity;
import com.lzw.bluetoothpractice.Activitys.RecoveryScheActivity;
import com.lzw.bluetoothpractice.Activitys.SearchDeviceActivity;
import com.lzw.bluetoothpractice.Activitys.StepRecordActivity;
import com.lzw.bluetoothpractice.Adapters.UserReadMessageListAdapter;
import com.lzw.bluetoothpractice.AppConfig;
import com.lzw.bluetoothpractice.Models.Kneel;
import com.lzw.bluetoothpractice.Models.Temperature;
import com.lzw.bluetoothpractice.MyApplication;
import com.lzw.bluetoothpractice.R;
import com.lzw.bluetoothpractice.Utils.AppUtil;
import com.lzw.bluetoothpractice.Utils.SharePreferenceUtils;
import com.lzw.bluetoothpractice.bean.KneelBean;
import com.lzw.bluetoothpractice.bean.SystemUserListBean;
import com.lzw.bluetoothpractice.bean.TemperatureBean;
import com.lzw.bluetoothpractice.network.HeadAssmblyUtils;
import com.lzw.bluetoothpractice.network.RetrofitManager;
import com.lzw.bluetoothpractice.network.api.RequestApi;

import java.lang.reflect.Array;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.lzw.bluetoothpractice.MyApplication.getContext;


public class ShouyeFragment extends Fragment implements OnClickListener {
    private Map<String, String> keyMap;
    private AAChartView aaChartView;
    private AAChartView aaChartView1;
    View view;
    Button btWalk,angle;
    Button btForum;
    Button bthealthyMEssage;
    Button btMyDoctor;
    Button online;
    private Object[] array;
    private Object[] kneel;

    private Handler mHander=new Handler();
    List<Object> list1= new ArrayList<Object>();
    List<Object> list2= new ArrayList<Object>();

    //LayoutInflater是用来找layout下xml布局文件
    //viewgroup是用来控制view如何摆放的，就好比view是玻璃，viewgroup是玻璃框的道理。
    //Bundle，是Android开发中的一个类，用于Activity之间传输数据用。
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,  Bundle savedInstanceState){
        view = inflater.inflate(R.layout.shouye,null);
       //btWalk=view.findViewById(R.id.walk);

      //  device=view.findViewById(R.id.device);
        online=view.findViewById(R.id.online);

        aaChartView = view.findViewById(R.id.AAChartView);
        aaChartView.aa_drawChartWithChartModel(arearangeMixedLine());
        aaChartView1 = view.findViewById(R.id.AAChartView1);
        aaChartView1.aa_drawChartWithChartModel(configureArearangeChart());
        mHander.post(timeRunable);



        online.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(getActivity(), DoctorsOnlineActivity.class);
                startActivity(intent);
            }
        });

        bthealthyMEssage=view.findViewById(R.id.bthealthyMEssage);
        bthealthyMEssage.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent=new Intent(getActivity(), HealthyMessagesActivity.class);
                startActivity(intent);
            }
        });
        btForum=view.findViewById(R.id.btForum);
        btForum.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent=new Intent(getActivity(), RecoveryForumActivity.class);
                startActivity(intent);
            }
        });

        btMyDoctor=view.findViewById(R.id.btMyDoctor);
        btMyDoctor.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent=new Intent(getActivity(), MyDoctorsActivity.class);
                startActivity(intent);
            }
        });

        return view;
    }

    private Runnable timeRunable = new Runnable() {
        @Override
        public void run() {

            initMyDoctor();

            initTemp();
            mHander.postDelayed(this, 1*60*1000);



        }

    };
    AAChartModel configureArearangeChart()  {
      //  initMyDoctor();
        return new AAChartModel()
                .chartType(AAChartType.Areaspline)
                .dataLabelsEnabled(true)
                .yAxisLabelsEnabled(true)
                .xAxisLabelsEnabled(false)
                .gradientColorEnable(true)
                .title("")
                .yAxisTitle("")
                .legendEnabled(false)
                .yAxisGridLineWidth(0f)
                .scrollablePlotArea(
                        new AAScrollablePlotArea()
                                .minWidth(500)
                                .scrollPositionX(1f)
                )
                .series(new AASeriesElement[]{
                        new AASeriesElement()
                                .name("屈膝度")
                                .data(kneel)

                });
    }
/*

* */




    AAChartModel arearangeMixedLine() {

        AADataElement singleSpecialData1 = new AADataElement()
                .marker(new AAMarker()
                        .fillColor("#D81B60")
                        .lineColor("#D81B60")//外沿线的颜色(用来设置折线连接点的轮廓描边颜色，当值为空字符串时，默认取数据点或数据列的颜色)

                )
                .color("#D81B60")
                .y(39.5f);
        Map linearGradientColor = AAGradientColor.linearGradient(
                AALinearGradientDirection.ToBottom,
                "rgba(212,233,253,1)",
                "rgba(254,254,254,0)"
        );


//        initTemp();

        AASeriesElement element1 = new AASeriesElement()
                .name("温度")
                .fillColor(linearGradientColor)
                .data(array)
               ;
        return new AAChartModel()
                .chartType(AAChartType.Areaspline)
                .yAxisMax(40.0f)
                //y轴最小值
                .yAxisMin(20.0f)
                .dataLabelsEnabled(true)
                .yAxisLabelsEnabled(true)
                .xAxisLabelsEnabled(false)
                .gradientColorEnable(true)
                .title("")
                .yAxisTitle("")
                .legendEnabled(false)
                .yAxisGridLineWidth(0f)
                .scrollablePlotArea(
                        new AAScrollablePlotArea()
                                .minWidth(500)
                                .scrollPositionX(1f)
                )
                .series(new AASeriesElement[]{element1});
    }


    private void initMyDoctor(){
        try {
            keyMap = HeadAssmblyUtils.HeadAssembly("/dev-api/android/kneel/researchByUserId");
        } catch (Exception e) {
            e.printStackTrace();
        }
        String accessToken = SharePreferenceUtils.getString(getContext(),"access_token",null);;
        String userid = SharePreferenceUtils.getString(getContext(),"userId",null);
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).getKneel(Long.parseLong(userid),"1", AppUtil.getVersionCode() + "", accessToken ,keyMap.get("gmtStr"), keyMap.get("contentMD5"), keyMap.get("hmacCode")).
                observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

                Log.e("屈膝度：",e.getMessage()+"");

            }

            @Override
            public void onNext(JSONObject json) {

                list1.clear();
                KneelBean kneelBean = JSON.parseObject(json.toString(), KneelBean.class);
                if(kneelBean.getCode()==200){

                    for (Kneel list2:kneelBean.getData()
                         ) {

                       list1.add(Double.parseDouble(list2.getKneel()));

                    }



                    List<Object> list= new ArrayList<Object>(list1);
                    kneel = (Object[])list.toArray(new Object[list1.size()]);

                    AASeriesElement[] aaSeriesElements=new AASeriesElement[]{
                            new AASeriesElement()
                                    .data(kneel)
                    };


                    aaChartView1.aa_onlyRefreshTheChartDataWithChartOptionsSeriesArray(aaSeriesElements);



                }else {
                    Toast toast=Toast.makeText(getContext(),"查询屈膝度失败",Toast.LENGTH_LONG);
                    toast.show();
                }


            }
        });

    }


    private void initTemp(){
        try {
            keyMap = HeadAssmblyUtils.HeadAssembly("/dev-api/android/temperature/researchByUserId");
        } catch (Exception e) {
            e.printStackTrace();
        }
        String accessToken = SharePreferenceUtils.getString(getContext(),"access_token",null);;
        String userid = SharePreferenceUtils.getString(getContext(),"userId",null);
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).getTemperature(Long.parseLong(userid),"1", AppUtil.getVersionCode() + "", accessToken ,keyMap.get("gmtStr"), keyMap.get("contentMD5"), keyMap.get("hmacCode")).
                observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

                Log.e("屈膝度：",e.getMessage()+"");

            }

            @Override
            public void onNext(JSONObject json) {

                list2.clear();
                TemperatureBean temperatureBean = JSON.parseObject(json.toString(), TemperatureBean.class);
                if(temperatureBean.getCode()==200){

                    for (Temperature list:temperatureBean.getData()
                    ) {

                        list2.add(list.getTemperature());

                    }



                    List<Object> list= new ArrayList<Object>(list2);
                    array = (Object[])list.toArray(new Object[list2.size()]);

                    AASeriesElement[] aaSeriesElements=new AASeriesElement[]{
                            new AASeriesElement()
                                    .data(array)
                    };


                    aaChartView.aa_onlyRefreshTheChartDataWithChartOptionsSeriesArray(aaSeriesElements);



                }else {
                    Toast toast=Toast.makeText(getContext(),"查询屈膝度失败",Toast.LENGTH_LONG);
                    toast.show();
                }


            }
        });

    }

    @Override
    public void onClick(View view) {

        }

}
